package com.offcn.login;

import com.offcn.dao.StudentDao;
import com.offcn.entity.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
//插入学生信息操作
@MultipartConfig
@WebServlet("/insert")
public class InsertServlet extends HttpServlet {
    //实例化StudentDao
    StudentDao sd = new StudentDao();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取页面中输入的学生信息
        String name = req.getParameter("name");
        String age = req.getParameter("age");
        String tel = req.getParameter("tel");
        String bir = req.getParameter("bir");
        String sex = req.getParameter("sex");
        Part part = req.getPart("spic");
        //获取图片信息的名字
        String filename = part.getSubmittedFileName();
        //给图片重新命名
        filename = UUID.randomUUID()+filename;
        //图片的保存路径
        String path = "d:/pic";
        //实例化Student，并将获取的学生信息传入
        Student student = new Student(name,Integer.parseInt(age),tel,DateUtil.dateformat(bir),Integer.parseInt(sex),filename);
        //调用插入学生信息方法，将信息传入数据库
        boolean b = sd.insert(student);
        if(b){
            //如果插入成功，则创建文件夹存储图片，并跳转回主页面
            File f = new File(path);
            if(!f.exists()){
                f.mkdir();
            }
            part.write(path+File.separator+filename);
            resp.sendRedirect("student");
        }
    }
}
